﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using ZHDJ.PayFactory.AliPayModel;
using System.Data;
using ZHDJ.Data.Models.Center;
using ZHDJ.Data;
using ZHDJ.Data.BLL;

namespace ZHDJ.Web.Portal
{
    public partial class return_url : System.Web.UI.Page
    {
        DataTable dt = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            SortedDictionary<string, string> sPara = GetRequestGet();

            if (sPara.Count > 0)//判断是否有带返回参数
            {
                AlipayNotify aliNotify = new AlipayNotify();
                bool verifyResult = aliNotify.Verify(sPara, Request.QueryString["notify_id"], Request.QueryString["sign"]);

                if (verifyResult)//验证成功
                {
                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    //请在这里加上商户的业务逻辑程序代码


                    //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
                    //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表

                    //商户订单号
                    string out_trade_no = Request.QueryString["out_trade_no"];

                    //支付宝交易号
                    string trade_no = Request.QueryString["trade_no"];

                    //交易状态
                    string trade_status = Request.QueryString["trade_status"];

                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //如果有做过处理，不执行商户的业务程序
                    if (Request.QueryString["trade_status"] == "TRADE_FINISHED" || Request.QueryString["trade_status"] == "TRADE_SUCCESS")
                    {
                        //批量修改订单状态
                        dt = PartyMemberCost.GetMemberCostListByOrderNumber(out_trade_no);
                        foreach (DataRow item in dt.Rows)
                        {
                            PartyMemberCost current = DB.PartyMemberCosts.Find(item["ID"]);
                            current.ModifyTime = DateTime.Now;
                            current.Status = 4;
                            if (DB.SaveChanges() > 0)
                            {
                                //增加积分
                                PartyScoreHelper.Add(() => PartyScoreHelper.AddMemberCost(current.LoginID, current.LoginID, current.ID, string.Format("{0}-{1}-01", current.Year, current.Month)));
                            }
                        }
                    }
                    else
                    {
                        Response.Write("trade_status=" + Request.QueryString["trade_status"]);
                    }
                    //支付成功返回首页
                    Response.Write("<script language='javascript'>window.location='../Default.aspx'</script>");
                }
                else//验证失败
                {
                    Response.Write("验证失败");
                }
            }
            else
            {
                Response.Write("无返回参数");
            }
        }

        /// <summary>
        /// 获取支付宝GET过来通知消息，并以“参数名=参数值”的形式组成数组
        /// </summary>
        /// <returns>request回来的信息组成的数组</returns>
        public SortedDictionary<string, string> GetRequestGet()
        {
            int i = 0;
            SortedDictionary<string, string> sArray = new SortedDictionary<string, string>();
            NameValueCollection coll;
            //Load Form variables into NameValueCollection variable.
            coll = Request.QueryString;

            // Get names of all forms into a string array.
            String[] requestItem = coll.AllKeys;

            for (i = 0; i < requestItem.Length; i++)
            {
                sArray.Add(requestItem[i], Request.QueryString[requestItem[i]]);
            }

            return sArray;
        }

        #region 实体上下文
        /// <summary>
        /// 数据访问 
        /// </summary>
        public static AppBoxContext DB
        {
            get
            {
                if (!HttpContext.Current.Items.Contains("__AppBoxContext"))
                {
                    HttpContext.Current.Items["__AppBoxContext"] = new AppBoxContext();
                }
                return HttpContext.Current.Items["__AppBoxContext"] as AppBoxContext;
            }
        }
        #endregion
    }
}